/**
 * 核心技术支持
 * IT渠道网 小程序商城
 * 13873174181 微信同号
 */
import {Base} from '../../utils/base.js';

class Cart extends Base {
    constructor(){
        super();
        this._storageKeyName = 'cart';
    };
    /*
     * 获取购物车
     * flag - {bool} 是否已选 [{id, name, main_img_url, price, +counts, +selectStatus},]
     */
    getCartDataFromLocal(flag) {
        var res = wx.getStorageSync(this._storageKeyName);
        if(!res){
            res = [];
            return res;
        }
        // 获取已选
        if(flag){
            for(let i=res.length-1; i>=0; i--){
                var list = res[i].orderItemList;
                for(let j=list.length-1; j>=0; j--){
                    if(!list[j].selectStatus){
                        list.splice(j,1) // 移除单品
                    }
                }
                if(list.length == 0){
                    res.splice(i,1) // 移除店铺
                }
            }
        }
        return res;
    };
    /*
     * 获取优惠券
     */
    findPayCoupon(sellerId, callback) {
        var allParams = {
            url: 'min/user/findPayCoupon?sellerId=' + sellerId,
            sCallback: function (data) {
                callback && callback(data);
            }
        }
        this.request(allParams);
    }
    /*
     * 获得 counts1总数, counts2总类
     * flag - {bool} 是否已选
     */
    getCartTotalCounts(flag) {
        var data = this.getCartDataFromLocal(),
            counts1 = 0,
            counts2 = 0;
        for(var i in data){
            var list = data[i].orderItemList;
            // 区分:选中总数 未选中总数
            if (flag){
                for(var j in list){
                    if(list[j].selectStatus) { // 选中的,会加此字段
                        counts1 += list[j].num;
                        counts2++;
                    }
                }
            }else{
                for(var k in list){
                    counts1 += list[k].num;
                    counts2++;
                }
            }
        }
        return {
          counts1: counts1,
          counts2: counts2
        };
    };
    /*
     * 本地缓存 保存,更新
     */
    execSetStorageSync(data) {
        wx.setStorageSync(this._storageKeyName, data);
    };
    /*
     * 加入到购物车
     * {id:, name:, main_img_url:, price:}, 购买数量
     */
    add(item, counts) {
        var cartData = this.getCartDataFromLocal();
        if (!cartData) {
            cartData = [];
        }
        var sellerId = item.sellerId;
        // 判断cartData内sellerId是否存在
        var cart = null;
        for (var i in cartData) {
            if (cartData[i].sellerId == sellerId) {
                cart = cartData[i];
                break;
            }
        }
        // 商家不存在, 新增商品到购物车列表
        if (cart == null) {
            // 创建购物车对象
            var cart = {}; // {sellerId:'', sellerName:'', orderItemList:[]}
            cart['sellerId'] = item.sellerId;
            cart['sellerName'] = item.seller;
            cart['selectStatus'] = false;
            var orderItemList = []; // [{id:'',},]
            var orderItem1 = this.createOrderItem(item, counts);
            orderItemList.push(orderItem1);
            cart['orderItemList'] = orderItemList;
            // 增加
            cartData.unshift(cart);
        } else {
            // 商家存在,
            // 获取商品明细列表并判断
            var orderItem = null;
            for (var i in cart.orderItemList) {
                if (cart.orderItemList[i].itemId == item.id) {
                    orderItem = cart.orderItemList[i];
                }
            }
            // 商品不存在, 增加新明细
            if (orderItem == null) {
                orderItem = this.createOrderItem(item, counts);
                cart.orderItemList.unshift(orderItem);
            } else {
                // 商品存在, 处理数量金额
                // 更改数量
                orderItem.num = orderItem.num + counts;
                // 更新金额
                orderItem.totalFee = orderItem.price * orderItem.num;
            }
        }
        this.execSetStorageSync(cartData); // 更新本地缓存
        return cartData;
    };
    /**
     * 创建购物车明细对象
     */
    createOrderItem(item, counts) {
        // 创建新的购物车明细对象
        var orderItem = {},
            obj = JSON.parse(item.spec),
            arr = [];
        for (var i in obj) { arr.push(obj[i]) };
        orderItem['goodsId'] = item.goodsId;
        orderItem['itemId'] = item.id;
        orderItem['num'] = counts;
        orderItem['stock'] = item.num;
        orderItem['picPath'] = item.image;
        orderItem['price'] = item.price;
        orderItem['sellerId'] = item.sellerId;
        orderItem['title'] = item.title;
        orderItem['spec'] = arr.toString();
        orderItem['totalFee'] = item.price * counts;
        orderItem['selectStatus'] = false; // 选中项
        return orderItem;
    };
    /*
     * 以下_可离开更新本地缓存
     * 修改商品数量
     * id - {int} 商品id
     * counts -{int} 数量
     */
    _changeCounts(id, counts) {
        var cartData = this.getCartDataFromLocal();
        // 更新单品数量
        for(var i in cartData){
            var list = cartData[i].orderItemList;
            for(var j in list){
                if(list[j].itemId == id){
                    if(list[j].num>0){
                        list[j].num += counts;
                    }else{
                        return;
                    }
                }
            }
        }
        this.execSetStorageSync(cartData);
    };
    /*
     * 增加商品数目
     *
     */
    addCounts(id) {
        this._changeCounts(id,1);
    };
    /*
     * 购物车减
     *
     */
    cutCounts(id) {
        this._changeCounts(id,-1);
    };
    /*
     * 删除某些商品
     */
    delete(ids) {
        var cartData = this.getCartDataFromLocal();
        for(let i=cartData.length-1; i>=0; i--){
            var list = cartData[i].orderItemList;
            for(let j=list.length-1; j>=0; j--){
                if(ids.indexOf(list[j].itemId)>-1){ // 校验单品状态
                    list.splice(j,1); // 移除
                }
            }
            // 校验店铺单品为空
            if(list.length == 0){
                cartData.splice(i,1); // 移除店铺
            }
        }
        this.execSetStorageSync(cartData);
    };
}

export {Cart};